'use strict'
$(function () {
    query()
    let id = location.search.split('?')[1]
    if (id) {
        getproduct(id).then(data => {
            $('[name=id]').val(data[0].id)
            $('[name=name]').val(data[0].name)
            $('[name=price]').val(data[0].price)

        })
    }
})
function query() {
    let keyword = $('[name=keyword]').val()
    getproduct(keyword).then(data => {
        rendata(data)
    })
}
function rendata(res) {
    let tr = $('.tr')
    tr.remove()
    res.forEach(item => {
        let html = `
        <tr class="tr" key="${item.id}">
        <td>${item.id}</td>
        <td>${item.name}</td>
        <td>${item.price}</td>
        <td>
            <input type="button" name="" id="" value="edit" onclick="edit(${item.id})">
            <input type="button" name="" id="" value="delete" onclick="del(${item.id})">
        </td>
        </tr>
        `
        $('#tb').append(html)
    });
}
function add() {
    location.href = './addOrEdit.html'

}
function cencel() {
    location.href = './index.html'

}
function save() {
    let id = $('[name=id]').val()
    let name = $('[name=name]').val()
    let price = $('[name=price]').val()
    let obj = {
        id,
        name,
        price
    }
    if (id) {
        putproduct(obj, obj.id).then(data => {
            if (data.code === 1000) {
                location.href = './index.html'

            } else {
                alert('gg')
            }
        })
    } else {
        postproduct(obj).then(data => {
            if (data.code === 1000) {
                location.href = './index.html'

            } else {
                alert('gg')
            }
        })
    }
}
function edit(id) {
    location.href = `./addOrEdit.html?${id}`
}
function del(id){
    let confirmd = confirm(`确认删除${id}吗？`)
    if(confirmd){
        delproduct(id).then(data=>{
            let id = data.data.id
            $(`[key=${id}]`).remove()
        })
    }
}